//
//  StrategyVC.m
//  NewNest
//
//  Created by 王阳阳 on 16/3/8.
//  Copyright © 2016年 www.lanou3g.com 蓝鸥科技. All rights reserved.
//

#import "StrategyVC.h"
#import "NewNestHeader.h"
#import "StrategyTableviewCell.h"
#import "StrategyModel.h"
#import "MyLoopsView.h"
#import "StrategyLunBoTu.h"
#import "StrategyViewCollectionViewCell.h"
#import "StratrgyDetailViewController.h"
#import "UserCell.h"
#import "FreeViewController.h"
#import "StrategyOtherViewController.h"
#import "StrateView.h"
#import "UIColor+UIColor.h"
@interface StrategyVC ()<UITableViewDelegate, UITableViewDataSource,UICollectionViewDataSource, UICollectionViewDelegate, pushActionDelegate>
@property (nonatomic, strong)UITableView *tableview;//tableview
@property (nonatomic, strong)NSMutableArray *dataArr;//tableview数组
@property (nonatomic, strong) UIButton *sortButton;/**< 分类的按钮 */
@property (nonatomic, assign) NSInteger sortNumber;/**< 装修攻略分类的数值 */
@property (nonatomic, strong) NSMutableArray *urlArr;//轮播图数组
@property (nonatomic, strong) UIView *sortView;/**< 分类的小视图 */
@property (nonatomic, strong) UICollectionView *collectionview;/**< 分类的collectionview */
@property (nonatomic, assign) NSInteger number;/**< 用来保存上拉加载时变化的数字 */
@property (nonatomic, strong) UIView *bigView;//装轮播图和CollectionView的View
@end

@implementation StrategyVC


- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    //    self.view.backgroundColor = [UIColor whiteColor];//背景颜色
    self.navigationItem.title = @"装修攻略";//navigation名字
    [self dataHandler];//数据处理
    [self creatSubviews];//视图初始化
    self.sortNumber = 0;//分类视图collectionView点击tableview变换的数据初始值
    //给保存上拉加载的数字设置初始值
    self.number = 2;
    [self creatBigCol];//Tableviw的创建
    [self refresh];
 
}
- (void)creatSubviews{
#pragma mark - /创建Tableview
    self.tableview = [[UITableView alloc]initWithFrame:self.view.frame style:UITableViewStylePlain];
    _tableview.dataSource = self;//代理人
    _tableview.delegate = self;
    _tableview.backgroundColor = [UIColor clearColor];//清空背景颜色
    [self.view addSubview:_tableview];
    [_tableview registerClass:[StrategyTableviewCell class] forCellReuseIdentifier:@"cell"];//重用池
#pragma mark - // 创建右上方分类的按钮
    self.sortButton = [UIButton buttonWithType:UIButtonTypeCustom];
    _sortButton.frame = CGRectMake(0, 0, 25, 25);
    [_sortButton setImage:[UIImage imageNamed:@"xiangxia@2x"] forState:UIControlStateNormal];
    [_sortButton setImage:[UIImage imageNamed:@"xiangshang@2x"] forState:UIControlStateSelected];
    // 按钮的点击方法
    [_sortButton addTarget:self action:@selector(pop) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:_sortButton];
#pragma mark - // 弹出的分类视图
    self.sortView = [[UIView alloc] initWithFrame:CGRectMake(0, 64, self.view.frame.size.width, [UIScreen mainScreen].bounds.size.height / 2)];
    _sortView.hidden = YES;//隐藏
    [self.view addSubview:_sortView];
#pragma mark - // 分类视图的背景图片
    UIImageView *backImg = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, _sortView.frame.size.width, _sortView.frame.size.height)];
    backImg.image = [UIImage imageNamed:@"backImg8.jpg"];//背景图片
    [_sortView addSubview:backImg];
#pragma mark - // 分类视图上的collectionView
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
    self.collectionview = [[UICollectionView alloc] initWithFrame:_sortView.bounds collectionViewLayout:layout];//布局
    layout.itemSize = CGSizeMake((_sortView.frame.size.width - 40) / 3, _sortView.frame.size.height / 10);//item大小
    layout.sectionInset = UIEdgeInsetsMake(5, 5, 5, 5);//边距
    [self.sortView addSubview:_collectionview];//代理
    _collectionview.delegate = self;
    _collectionview.dataSource = self;
    _collectionview.backgroundColor = [UIColor clearColor];//清空背景颜色
    [_collectionview registerClass:[StrategyViewCollectionViewCell class] forCellWithReuseIdentifier:@"cell"];//重用池
}
#pragma mark - tableview必须实现的两个方法
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return  _dataArr.count;//数组个数
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    StrategyTableviewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell" forIndexPath:indexPath];
    [cell setSelectionStyle:UITableViewCellSelectionStyleNone];

    cell.backgroundColor = [UIColor clearColor];
    // 判断当前是什么模式
    BOOL model = [AccountManager sharedInstance].isNight;
    if (model == YES) {
        cell.backgroundColor = [UIColor changeColorWithString:@"#a1a3a6"];
        
    } else {
        cell.backgroundColor = [UIColor clearColor];
    }
    cell.model = _dataArr[indexPath.row];//传出值得Model
    return cell;
}
#pragma mark - collectionView必须实现的两个方法
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
        return 21;
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    
        //判断collectionView 如果是分类视图执行分类视图的cell样式
        StrategyViewCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"cell" forIndexPath:indexPath];
        //名字数组
        NSArray *arr = @[@"装修选材",@"验房须知",@"装修合同",@"装修预算",@"装修风水",@"装修设计",@"装修要点",@"装修选材",@"建材安装",@"拆改工程",@"水电工程",@"防水工程",@"泥瓦工程",@"水木工程",@"油漆工程",@"装修污染",@"装修验收",@"家居护理",@"家居配饰",@"家电家私",@"取消筛选"];//cell显示的数据数组
        cell.titleLabel.text = arr[indexPath.item];//赋值
        return cell;
    
}
#pragma mark - collectionView点击事件
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{

        //判断collectionView 如果是分类视图执行分类视图的点击方法  改变tableview的分类
        NSArray *arr = @[@20,@19,@18,@17,@16,@15,@14,@13,@12,@11,@10,@9,@8,@7,@6,@5,@4,@3,@2,@1,@0];
        self.sortNumber = [arr[indexPath.row] integerValue];
        [self dataHandler];
        // 收起视图 改变按钮状态
        self.sortButton.selected = NO;
        self.sortView.hidden = YES;
        // 让tableview回到顶端
        [self.tableview setContentOffset:CGPointMake(0, -64) animated:YES];
    
}
#pragma mark - 数据处理
- (void)dataHandler{
    //tableview数据
    NSString *str = [NSString stringWithFormat:@"http://api.guju.com.cn/v2/strategy/strategyList?userId=0&count=10&start=0&orderString=CATEGORY&category=%ld", (long)self.sortNumber];
    [AFNetworking GETWithURL:str completion:^(id result) {
        NSMutableArray *arr = result[@"strategyList"];
        self.dataArr = [StrategyModel modelHanderWithArray:arr];
        [_tableview reloadData];
        NSLog(@"%@",self.dataArr);
    }];
    //轮播图数据
    NSString *urlStr = @"http://api.guju.com.cn/v2/strategy/banner";
    [AFNetworking GETWithURL:urlStr completion:^(id result) {
        NSMutableArray *arr = result[@"banners"];
        self.urlArr = [StrategyLunBoTu modelHanderWithArray:arr];
        //设置上方的轮播图
        NSMutableArray *carouseArr = [NSMutableArray array];
        for (NSInteger i = 0; i < _urlArr.count; i++) {
            StrategyLunBoTu *m = _urlArr[i];
            NSString *str = m.phoneImgUrl;
            [carouseArr addObject:str];
        }
        //创建轮播图并添加
        
        MyLoopsView *carouse = [[MyLoopsView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 180) imageArr:carouseArr];
       
            //定义一个block 用于跳转不同的页面
            void(^MyBlock)(NSInteger selectedNum) = ^(NSInteger selectedNum){
                NSLog(@"好使");
                //跳转至详情页面
                StratrgyDetailViewController *detailVC = [[StratrgyDetailViewController alloc] init];
                StrategyLunBoTu *modal = _urlArr[selectedNum];
                detailVC.idStr = modal.strategyId;
                // 说明是轮播图传过去的数据
                detailVC.carouse = YES;
                [detailVC.navigationController pushViewController:detailVC animated:YES];
            };
            //将定义好的block通过属性的方法传递
            carouse.block = MyBlock;
        //将轮播图放置在tableview头部
        [self.tableview addSubview:carouse];
        [self.tableview reloadData];
        }];
    
    [self.tableview.mj_header endRefreshing];
}
#pragma mark - 刷新加载
- (void)refresh{
    self.tableview.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(dataHandler)];
    [self.tableview.mj_header beginRefreshing];
    self.tableview.mj_footer = [MJRefreshAutoFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadNewData)];
    if (_dataArr.count !=0) {
        [self.tableview.mj_footer beginRefreshing];
    }
}


- (void)loadNewData{
    NSString *urlStr = [NSString stringWithFormat:@"http://api.guju.com.cn/v2/strategy/strategyList?userId=0&count=10&start=%ld&orderString=CATEGORY&category=0",(long)self.number];
    [AFNetworking GETWithURL:urlStr completion:^(id result) {
        // 创建新数组用以接收新的数据
        NSArray *newDataArr = [NSArray array];
        newDataArr = [StrategyModel modelHanderWithArray:result[@"strategyList"]];
        //将新的数据依次加入保存数据的数组里面
        for (NSInteger i = 0; i < 10; i++) {
            [_dataArr addObject:newDataArr[i]];
        }
        // 刷新tableView
        [self.tableview reloadData];

    }];
    [self.tableview.mj_footer endRefreshing];
    self.number += 10;
}
#pragma mark - 导航栏右侧分类按钮的点击方法
- (void)pop{
    _sortButton.selected = !_sortButton.selected;
    if (_sortButton.selected == YES) {
        // 给分类的view添加动态
        [UIView animateWithDuration:1 animations:^{
            self.sortView.center = CGPointMake(_sortView.center.x, [UIScreen mainScreen].bounds.size.height / 4 + 64);
        }];
        _sortView.hidden = NO;
    }else {
        [UIView animateWithDuration:1 animations:^{
            self.sortView.center = CGPointMake(_sortView.center.x, -[UIScreen mainScreen].bounds.size.height / 4);
        } completion:^(BOOL finished) {
            self.sortView.hidden = YES;
        }];
    }
}
#pragma mark - cell的高度
- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return [UIScreen mainScreen].bounds.size.height / 3.5;
}
#pragma mark - Tableview点击事件
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    StratrgyDetailViewController *stratrgy = [[StratrgyDetailViewController alloc]init];
    StrategyModel *m = _dataArr[indexPath.row];
    stratrgy.idStr = m.detailId;
    stratrgy.mainModal = m;
    [self.navigationController pushViewController:stratrgy animated:YES];
}
#pragma mark - bigCollectionView的创建
- (void)creatBigCol{
    //装轮播图和collectionView的View
    self.bigView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 320)];
    [self.tableview addSubview:self.bigView];
    self.bigView.backgroundColor = [UIColor clearColor];
    self.tableview.tableHeaderView = _bigView;
    //分类的自定义View
    StrateView *classify = [[StrateView alloc]initWithFrame:CGRectMake(0,180, self.view.frame.size.width, 150)];
    classify.delegate = self;
    classify.backgroundColor = [UIColor clearColor];
    [self.bigView addSubview:classify];
   
}

- (void)pushWebAction:(NSString *)name
{
    FreeViewController *free = [[FreeViewController alloc]init];
    free.titlename = name;//下一页导航栏title显示的名字
    [self.navigationController pushViewController:free animated:YES];
}
#pragma mark - 代理页面跳转
- (void)pushAction:(NSString *)str Name:(NSString *)name
{
    StrategyOtherViewController *other = [[StrategyOtherViewController alloc]init];
    other.titlename = name;//传值到下一页的导航栏名字
    other.str = str;
    [self.navigationController pushViewController:other animated:YES];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
